#include <stdio.h>
#include <unistd.h>
#include "ohos_init.h"
#include "ohos_types.h"
#include "cmsis_os2.h"
#include "iot_errno.h"
#include "iot_gpio.h"
#include "iot_gpio_ex.h"
#include "iot_adc.h"

#define KEY_GPIO 7
#define ADC_CHANNEL 3

// 获取电压
static float GetVoltage(void)
{
    unsigned short data;
    unsigned int ret = IoTAdcRead(ADC_CHANNEL, &data, IOT_ADC_EQU_MODEL_8, IOT_ADC_CUR_BAIS_DEFAULT, 0xff);
    if (ret != IOT_SUCCESS)
    {
        printf("ADC Read Fail!\n");
    }
    return (float) data * 1.8 * 4 / 4096.0;
}

static void ADCTask(void)
{
    float voltage;
    // 初始化 GPIO7
    IoTGpioInit(KEY_GPIO);
    // 将 GPIO7 设置为上拉，使按键未按下时保持高电平状态
    IoTGpioSetPull(KEY_GPIO, IOT_GPIO_PULL_UP);
    while (1)
    {
        // 获取电压值
        voltage = GetVoltage();
        // 将电压值输出到串口
        printf("Voltage: %.3fV\n", voltage);
        // 延时 1s
        sleep(1);
    }
}

void ADCExample(void)
{
    osThreadAttr_t attr;
    attr.name = "ADCTask";
    attr.attr_bits = 0U;
    attr.cb_mem = NULL;
    attr.cb_size = 0U;
    attr.stack_mem = NULL;
    attr.stack_size = 1024;
    attr.priority = osPriorityNormal;
    if (osThreadNew((osThreadFunc_t) ADCTask, NULL, &attr) == NULL)
    {
        printf("Failed to create ADCTask!\n");
    }
}

SYS_RUN(ADCExample);
